package surreal.triviamaster.gui;

import surreal.triviamaster.R;
import surreal.triviamaster.beans.Category;
import surreal.triviamaster.database.LocalCache;
import surreal.triviamaster.utilities.TriviaMasterApplication;
import surreal.triviamaster.utilities.TriviaMasterService;
import surreal.triviamaster.utilities.Utilities;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class CategorySelector extends ListActivity{
	    
    private LocalCache db;
    private Category[] cats;
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	setContentView(R.layout.category_selector);
    	
    	db = ((TriviaMasterApplication) getApplication()).getLocalCache();
    	//getting cats and creating the string of cats
    	cats = db.getAllCategories();
    	String[] catList=new String[cats.length];
    	
    	for(int i=0;i<cats.length;i++) {
    		catList[i]=cats[i].getCategory();
    	}
    	setListAdapter(new ArrayAdapter<String>(this, R.layout.generic_list_item, catList));
    	
    	ListView lv = getListView();
    	lv.setTextFilterEnabled(true);

    	// When clicked, open that activity
    	lv.setOnItemClickListener(new OnItemClickListener() {
    		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    			if(Utilities.isNetworkAvailable(CategorySelector.this)) {
	            	//setting the quiz to have the given category
	    			db.setCurrentQuizCategory(cats[position].getId());
	    			Log.d("CategorySelector", "Before Service Call, catId: "+cats[position].getId());
	    			//getting the quiz questions from server
	    			Intent intent = new Intent(TriviaMasterApplication.ACTION_GET_QUESTIONS, null, CategorySelector.this, TriviaMasterService.class);
	    			startService(intent);
	    			Log.d("CategorySelector", "After Service Call, catId: "+cats[position].getId());
	    			
					//loading the game activity
			    	intent = new Intent(CategorySelector.this, LoadingScreen.class);
					startActivity(intent);
            	} else {
            		Toast.makeText(CategorySelector.this, TriviaMasterApplication.NETWORK_ERROR, 5000);
            	}
	    	}
    	});    
    	
    	//Home button
	    Button home = (Button) findViewById(R.id.home);
	    home.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	
    				//Move user to next page
    		    	Intent intent = new Intent(CategorySelector.this, TriviaMasterActivity.class);
    	  	      	startActivity(intent);
            }
        });
	}
	
}
